import random
import string

from django.shortcuts import render, redirect, get_object_or_404, reverse
from django.http.response import JsonResponse
from django.core.mail import send_mail
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm , LoginForm
from django.contrib.auth import get_user_model , login, logout

# Create your views here.

User = get_user_model()


@require_http_methods(['GET', 'POST'])
def qflogin(request):
    if request.method == "GET":
        return render(request, template_name='login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request, user)
                # 判断是否需要记住我
                if not remember:
                    # 如果没有点击记住我，那么就要设置过期时间为0，即浏览器关闭后就会过期
                     request.session.set_expiry(0)
                # 如果点击了，那么就什么都不做，使用默认的2周的过期时间
                return redirect('/')
            else:
                print('邮箱或密码错误')
                # form.add_error('email','邮箱或密码错误!')
                # return render(request,'login.html',context={
                #     "form":form,
                # })
                return redirect(reverse('qiauth:login'))

def qilogout(request):
    logout(request)
    return redirect('/')

@require_http_methods(['GET', 'POST'])
def register(request):
   if request.method == 'GET':
        return render(request,template_name='register.html')
   else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            User.objects.create_user(username=username,email=email,password=password)
            return redirect(reverse('qiauth:login'))
        else:
            return redirect(reverse('qiauth:register'))

def send_email_captcha(request):
   # return render(request,)
    email = request.GET.get('email')
    if not email:
       return JsonResponse({"code":400,"message":'必须传递邮箱！'})
    #生成验证码
    captcha = "".join(random.sample(string.digits,k=4))
    # 存储到数据库中
    CaptchaModel.objects.update_or_create(email=email,defaults={'captcha':captcha})
    captcha = "".join(random.sample(string.digits, k=4))
    send_mail("起风了博客注册验证码",message=f"您的注册验证码是：{captcha}",recipient_list=[email],from_email=None)
    return JsonResponse({"code":200,"message":'邮箱验证码发送成功'})
